<template>
  <div class="canvas-wrapper draw-polygons">
    <!--用来和鼠标进行交互操作的canvas-->
    <canvas
      class="canvas-dom"
      @mousemove="MouseMove"
      @mousedown="clickPoint"
      @mouseup="stopDragging"
      :width="canvasWidth"
      :height="canvasHeight"
      ref="can"
    ></canvas>
    <!--存储已生成的点线，避免被清空-->
    <canvas
      class="canvasSave-dom"
      :width="canvasWidth"
      :height="canvasHeight"
      ref="canSave"
    ></canvas>
  </div>
</template>
<script setup>
// export const drawTypeEnum = object2Enum({
//     0: "lines",
//     1: "polygons",
// });
import { onUnmounted, ref, reactive, watchEffect, nextTick } from "vue";
import { cloneDeep } from "lodash";
import { drawTypeEnum } from "@/constant/dictionary";
import { debounce } from "@/utils/index.js";
import {
  isIntersect,
  polygonHasIntersectingLinesAllowingVertices,
} from "@/utils/math.js";
const can = ref(null);
const ctx = ref(null);
const canSave = ref(null);
const ctxSave = ref(null);
const pointX = ref(null);
const pointY = ref(null);
const drawEnd = ref(true); // 结束绘制
const isReset = ref(false); // 是否重置
const pointArr = ref([]); //存放坐标的数组
const oldPointArr = ref([]); //克隆拖拽前存放坐标的数组，便于拖拽相关逻辑实现
const pointArrSave = ref([]); //保存存放坐标的数组
const oIndex = ref(-1); //判断鼠标是否移动到起始点处，-1为否，1为是
const ctxFillStyle = ref("rgba(21, 119, 255, 0.30)"); // 填充颜色
const ctxSaveFillStyle = ref("rgba(21, 119, 255, 0.30)"); // 填充颜色
const arcFillStyle = ref("#1577FF"); // 圆点的填充颜色
const selectObject = ref(null); // 选择的拖动点在pointArrSave的位置
const isDragging = ref(false); // 是否可以拖动
let selectMovePoint = null; // 鼠标点在pointArrSave的位置
const pointSize = 4;
let debugFlag = false;
const res = reactive({
  0: [],
  1: [],
});
const props = defineProps({
  // 画布尺寸
  canvasWidth: {
    type: [Number, String],
    default: 1000,
  },
  canvasHeight: {
    type: [Number, String],
    default: 600,
  },
  // 底图尺寸
  imageWidth: {
    type: Number,
    default: null,
  },
  imageHeight: {
    type: Number,
    default: null,
  },
  // 底图分辨率尺寸
  naturalWidth: {
    type: Number,
    default: null,
  },
  naturalHeight: {
    type: Number,
    default: null,
  },
  // 多边形
  polygons: {
    type: Array,
    default: null,
  },
  // 可编辑
  editable: {
    type: Boolean,
    default: false,
  },
  // 保存点数据项是不是对象结构
  pointItemIsObj: {
    type: Boolean,
    default: false,
  },
  // 是否可撤销（没实现
  withdrawAble: {
    type: Boolean,
    default: false,
  },
  // 是否判断当前绘制点线和其他线段交叉
  judgePointIsIntersect: {
    type: Boolean,
    default: false,
  },
  // 是否判断当前绘制图形和其他图形重叠了（没实现
  judgeIsOverlapping: {
    type: Boolean,
    default: false,
  },
  // 判断点击点的容错距离，越大越容易点到实心点
  faultTolerant: {
    type: Number,
    default: 5,
  },
});
const emits = defineEmits(["pointIsIntersect", "rectIsOverlapping"]);
// 存储id和点信息对应关系
const savePointInfoOfId = [];
const drawTypeStyle = {
  [drawTypeEnum.lines]: {
    lineWidth: 2,
    maxCount: 2,
    maxPointCount: 2,
    dataTest:
      "[[[25,44],[213,156]],[[110,26],[37,99]],[[204,110],[206,31]],[[166,33],[80,159]],[[25,136],[186,82]]]",
  },
  [drawTypeEnum.polygons]: {
    lineWidth: 1,
    maxCount: 10,
    maxPointCount: 10,
    dataTest:
      "[[[16,5],[5,175],[256,2]],[[29,16],[129,173],[253,177],[253,48]],[[98,55],[31,111],[188,139]]]",
  },
};
watchEffect(() => {
  if (ctx.value) {
    ctx.value.lineWidth = drawTypeStyle[drawTypeEnum.polygons].lineWidth; //线条粗细
  }
  if (ctxSave.value) {
    ctxSave.value.lineWidth = drawTypeStyle[drawTypeEnum.polygons].lineWidth; //线条粗细
  }
  console.log(drawTypeEnum.polygons, "drawTypeEnum.polygons");
});

const init = (isResize) => {
  ctx.value = can.value.getContext("2d");
  ctxSave.value = canSave.value.getContext("2d");
  ctx.value.strokeStyle = "#1577FF"; //线条颜色
  ctx.value.lineWidth = drawTypeStyle[drawTypeEnum.polygons].lineWidth; //线条粗细
  ctxSave.value.strokeStyle = "#1577FF"; //线条颜色
  ctxSave.value.lineWidth = drawTypeStyle[drawTypeEnum.polygons].lineWidth; //线条粗细
  if (isResize) {
    ClickClear();
  }
  props.polygons?.length && drawPolygons(props.polygons);
  props.editable ? ClickDraw() : disabledDraw();
  can.value?.removeEventListener("contextmenu", onRightClick);
  can.value?.addEventListener("contextmenu", onRightClick);
};
onUnmounted(() => {
  can.value?.addEventListener("contextmenu", onRightClick);
});

const getCommonState = debounce((fromMsg) => {
  console.log(
    JSON.parse(JSON.stringify(pointArr.value)),
    fromMsg || "pointArr.value"
  );
}, 200);
// 获取缩放比例
const getZoomRatio = () => {
  debugFlag && console.log("getZoomRatio被调用");
  let width = parseInt(props.imageWidth || props.canvasWidth);
  let height = parseInt(props.imageHeight || props.canvasHeight);
  return {
    scaleX: props.naturalWidth / width,
    scaleY: props.naturalHeight / height,
  };
};
const makearc = (ctxObj, x, y, r, s, e, color) => {
  debugFlag && console.log("makearc被调用");
  // ctxObj.clearRect(0, 0, can.value.width, can.value.height); //清空画布 为了每个节点生成圆点，注释掉，不生成圆点需要取消注释
  ctxObj.beginPath();
  ctxObj.fillStyle = color;
  ctxObj.arc(x, y, r, s, e);
  ctxObj.fill();
};

// 为数组每个节点生成圆点
const drawMaker = (ctxObj, pointArrList, paramsObj) => {
  const { randomSize = pointSize, fillStyle = arcFillStyle.value } =
    paramsObj || {};
  for (let i = 0; i < pointArrList.length; i++) {
    makearc(
      ctxObj,
      pointArrList[i].x,
      pointArrList[i].y,
      GetRandomNum(
        pointArrList[i].randomSize ?? randomSize,
        pointArrList[i].randomSize ?? randomSize
      ),
      0,
      180,
      fillStyle
    );
  }
};
// rectPointList: [[x1, y1], [x2, y2], [x3, y3], [x4, y4]]
const judgeIsFullScreen = (rectPointList) => {
  if (!rectPointList || rectPointList.length !== 4) {
    return false;
  }
  const flag = rectPointList.every((item, idx) => {
    let res = false;
    switch (idx) {
      case 0:
        if (Array.isArray(item)) {
          res = item[0] === 0 && item[1] === 0;
        }
        break;
      case 1:
        if (Array.isArray(item)) {
          res =
            parseInt(item[0]) ===
              parseInt(props.imageWidth || props.canvasWidth) && item[1] === 0;
        }
        break;
      case 2:
        if (Array.isArray(item)) {
          res =
            parseInt(item[0]) ===
              parseInt(props.imageWidth || props.canvasWidth) &&
            parseInt(item[1]) ===
              parseInt(props.imageHeight || props.canvasHeight);
        }
        break;
      case 3:
        if (Array.isArray(item)) {
          res =
            item[0] === 0 &&
            parseInt(item[1]) ===
              parseInt(props.imageHeight || props.canvasHeight);
        }
        break;
      default:
        break;
    }
    return res;
  });
  return flag;
};

const onRightClick = (e) => {
  debugFlag && console.log("onRightClick被调用");
  // // 防止打开菜单菜单
  // e.stopPropagation();
  // e.preventDefault();

  // // 如果没有点 不用撤销
  // if (pointArr.value.length === 0) return;
  // pointArr.value.pop(); // 移除最后一个点
  // return false;
};
const judgeIsIntersect = (pointArrList) => {
  if (props.judgePointIsIntersect) {
    // 是否存在交叉项
    return polygonHasIntersectingLinesAllowingVertices(pointArrList);
  }
  return false;
};
/*canvas生成圆点*/
const GetRandomNum = (Min, Max) => {
  debugFlag && console.log("GetRandomNum被调用");
  let Range = Max - Min;
  let Rand = Math.random();
  return Min + Math.round(Rand * Range);
};
/*清空选区*/
const ClickClear = () => {
  debugFlag && console.log("ClickClear被调用");
  ctx.value.clearRect(0, 0, can.value.width, can.value.height);
  ctxSave.value.clearRect(0, 0, canSave.value.width, canSave.value.height);
  pointArr.value = [];
  res[drawTypeEnum.polygons] = [];
  drawEnd.value = true;
};
/*验证canvas画布是否为空函数*/
const isCanvasBlank = (canvas) => {
  debugFlag && console.log("isCanvasBlank被调用");
  let blank = document.createElement("canvas"); //创建一个空canvas对象
  blank.width = canvas.width;
  blank.height = canvas.height;
  return canvas.toDataURL() == blank.toDataURL(); //为空 返回true
};

// ---------------------------------------------------------------
// 存储已生成的点线
const canvasSave = (pointArr) => {
  debugFlag && console.log("canvasSave被调用");
  ctxSave.value.clearRect(0, 0, ctxSave.value.width, ctxSave.value.height);
  drawMaker(ctxSave.value, pointArr);
  ctxSave.value.beginPath();
  if (pointArr.length > 1) {
    ctxSave.value.moveTo(pointArr[0].x, pointArr[0].y);
    for (let i = 1; i < pointArr.length; i++) {
      ctxSave.value.lineTo(pointArr[i].x, pointArr[i].y);
      ctxSave.value.fillStyle = ctxSaveFillStyle.value; //填充颜色
    }
    // ctxSave.value.fill();
    ctxSave.value.stroke(); //绘制
    ctxSave.value.closePath();
  }
};
// 重新画图
const drawRects = (data) => {
  debugFlag && console.log("drawRects被调用");
  if (data) {
    isReset.value = false;
    ClickClear();
    data.forEach((item, index) => {
      ((props.pointItemIsObj ? item.positions : item) || []).forEach(
        (item1, index1) => {
          pointArr.value.push({ x: item1[0], y: item1[1] });
        }
      );
      canvasSave(pointArr.value); //保存点线同步到另一个canvas
      saveCanvas(); //生成画布
    });
  }
};
// 拖动重新画图
const dragCircle = (e) => {
  debugFlag && console.log("dragCircle被调用");
  // 判断是否可以拖动
  if (isDragging.value == true) {
    const positionObj = getSelectPosition();
    // 取得画布上被点击的点
    positionObj[selectObject.value[1]][0] = e.offsetX;
    positionObj[selectObject.value[1]][1] = e.offsetY;
    drawRects(res[drawTypeEnum.polygons]);
  }
};
// 鼠标附近的点变大
const highlightPoint = (e) => {
  if (res[drawTypeEnum.polygons].length > 0) {
    selectMovePoint = null;
    res[drawTypeEnum.polygons].forEach((item, index) => {
      const arrayDemo = (props.pointItemIsObj ? item.positions : item) || [];
      let x, y;
      if (e.offsetX || e.layerX) {
        x = e.offsetX ?? e.layerX;
        y = e.offsetY ?? e.layerY;
        for (let i = 0; i < arrayDemo.length; i++) {
          if (
            judgeInCircle(
              {
                x: arrayDemo[i][0],
                y: arrayDemo[i][1],
              },
              {
                x,
                y,
              },
              props.faultTolerant
            )
          ) {
            selectMovePoint = [index, i];
          }
        }
      }
    });
    if (selectMovePoint?.length) {
      const pointInfo = getMovePointPosition()[selectMovePoint[1]];
      pointInfo &&
        drawMaker(ctx.value, [
          {
            x: pointInfo[0],
            y: pointInfo[1],
            randomSize: pointSize + 2,
          },
        ]);
    }
  }
};
const getSelectPosition = () => {
  return props.pointItemIsObj
    ? res[drawTypeEnum.polygons][selectObject.value[0]].positions
    : res[drawTypeEnum.polygons][selectObject.value[0]];
};
const getMovePointPosition = () => {
  if (!selectMovePoint?.length) {
    return [];
  }
  return props.pointItemIsObj
    ? res[drawTypeEnum.polygons][selectMovePoint[0]].positions
    : res[drawTypeEnum.polygons][selectMovePoint[0]];
};
const setSelectPosition = (positions) => {
  if (props.pointItemIsObj) {
    res[drawTypeEnum.polygons][selectObject.value[0]].positions = positions;
  } else {
    res[drawTypeEnum.polygons][selectObject.value[0]] = positions;
  }
};
// 遍历元素在哪一个圆上
const circle = (e, Array, clientX, clientY, index) => {
  debugFlag && console.log("circle被调用");
  for (let i = 0; i < Array.length; i++) {
    if (
      judgeInCircle(
        {
          x: Array[i][0],
          y: Array[i][1],
        },
        {
          x: clientX,
          y: clientY,
        },
        props.faultTolerant
      )
    ) {
      isDragging.value = true;
      selectObject.value = [index, i];
      const positionObj = getSelectPosition();
      oldPointArr.value = cloneDeep(
        positionObj.map((item) => ({ x: item[0], y: item[1] }))
      );
    }
  }
};
// 判断点的位置是否在圆心为p1，半径为faultTolerant的圆里面
const judgeInCircle = (p1, p2, faultTolerant) => {
  // Math.abs返回绝对值
  // Math.sqrt返回一个数的平方根
  // Math.pow幂函数运算
  return (
    Math.abs(Math.sqrt(Math.pow(p1.x - p2.x, 2) + Math.pow(p1.y - p2.y, 2))) -
      faultTolerant <
    0
  );
};
// Canvas点击事件
// 遍历所有的坐标点
const clickPoint = (e) => {
  debugFlag && console.log("clickPoint被调用");
  if (res[drawTypeEnum.polygons].length > 0) {
    res[drawTypeEnum.polygons].forEach((item, index) => {
      circle(
        e,
        (props.pointItemIsObj ? item.positions : item) || [],
        e.offsetX,
        e.offsetY,
        index
      );
    });
  }
};
// -----------------------------
// 删除上一个图形
const DeletePrevious = () => {
  debugFlag && console.log("DeletePrevious被调用");
  if (res[drawTypeEnum.polygons].length <= 1) {
    // 清空
    ClickReset();
    return;
  }
  pointArr.value.pop();
  res[drawTypeEnum.polygons].pop();
  savePointInfoOfId.pop();
  canvasSave(pointArr.value); //保存点线同步到另一个canvas
  saveCanvas(); //生成画布
  //   重新画图
  drawRects(res[drawTypeEnum.polygons]);
};
// 绘制全屏
const drawFullScreen = () => {
  debugFlag && console.log("drawFullScreen被调用");
  if (
    res[drawTypeEnum.polygons].length >=
    drawTypeStyle[drawTypeEnum.polygons].maxCount
  ) {
    return;
  }
  drawEnd.value = true;
  let RatioInfo = getZoomRatio();
  [
    [0, 0],
    [props.imageWidth || props.canvasWidth, 0],
    [
      props.imageWidth || props.canvasWidth,
      props.imageHeight || props.canvasHeight,
    ],
    [0, props.imageHeight || props.canvasHeight],
  ].forEach((item) => {
    pointArr.value.push({
      x: item[0] / RatioInfo.scaleX,
      y: item[1] / RatioInfo.scaleY,
    });
    pointArrSave.value.push({
      x: item[0] / RatioInfo.scaleX,
      y: item[1] / RatioInfo.scaleY,
    });
  });
  canvasSave(pointArr.value); //保存点线同步到另一个canvas
  saveCanvas(); //生成画布
};
// 删除设置的全屏类型的多边形
const deleteFullScreen = () => {
  debugFlag && console.log("deleteFullScreen被调用");
  const findIdxList = [];
  (res[drawTypeEnum.polygons] ?? []).forEach((item, index) => {
    if (judgeIsFullScreen(props.pointItemIsObj ? item.positions : item)) {
      findIdxList.push(index);
    }
  });
  let idx = -1;
  for (let index = findIdxList.length; index > 0; index--) {
    idx = findIdxList[index];
    res[drawTypeEnum.polygons].splice(idx, 1);
    savePointInfoOfId.splice(idx, 1);
  }
  //   重新画图
  drawRects(res[drawTypeEnum.polygons]);
};
const drawPolygons = (arr) => {
  debugFlag && console.log("drawPolygons被调用");
  drawEnd.value = true;
  let RatioInfo = getZoomRatio();
  (arr || []).forEach((pointListObj) => {
    savePointInfoOfId.push(pointListObj);
    (
      (props.pointItemIsObj ? pointListObj.positions : pointListObj) || []
    ).forEach((item) => {
      pointArr.value.push({
        x: item[0] / RatioInfo.scaleX,
        y: item[1] / RatioInfo.scaleY,
      });
    });
    canvasSave(pointArr.value); //保存点线同步到另一个canvas
    saveCanvas(false); //生成画布
  });
};
// 绘制坐标
const ClickDraw = () => {
  debugFlag && console.log("ClickDraw被调用");
  if (
    res[drawTypeEnum.polygons]?.length >=
    drawTypeStyle[drawTypeEnum.polygons].maxCount
  ) {
    return;
  }
  drawEnd.value = false;
  isReset.value = false;
};
// 禁用绘制坐标
const disabledDraw = () => {
  debugFlag && console.log("disabledDraw被调用");
  drawEnd.value = true;
  isReset.value = true;
};
// 绘制线段坐标
const ClickDrawLine = () => {
  debugFlag && console.log("ClickDrawLine被调用");
  drawEnd.value = false;
  isReset.value = false;
};
// 生成坐标
const ClickSet = () => {
  debugFlag && console.log("ClickSet被调用");
  isReset.value = false;
  ClickClear();
  let dataTest = drawTypeStyle[drawTypeEnum.polygons].dataTest;
  let RatioInfo = getZoomRatio();
  JSON.parse(dataTest).forEach((item, index) => {
    item.forEach((item1, index1) => {
      pointArr.value.push({
        x: item1[0] / RatioInfo.scaleX,
        y: item1[1] / RatioInfo.scaleY,
      });
    });
    console.log("生成坐标", pointArr.value);
    canvasSave(pointArr.value); //保存点线同步到另一个canvas
    saveCanvas(); //生成画布
  });
};
// 重置坐标
const ClickReset = () => {
  debugFlag && console.log("ClickReset被调用");
  isReset.value = true;
  ClickClear();
};
// 提交坐标
const ClickPut = () => {
  debugFlag && console.log("ClickPut被调用");
  let RatioInfo = getZoomRatio();
  return (res[drawTypeEnum.polygons] || []).map((item, idx) => {
    return props.pointItemIsObj
      ? {
          ...item,
          ...(savePointInfoOfId[idx] || null),
          positions: item.positions.map((item) => [
            parseInt(item[0] * RatioInfo.scaleX),
            parseInt(item[1] * RatioInfo.scaleY),
          ]),
        }
      : item.map((item) => [
          parseInt(item[0] * RatioInfo.scaleX),
          parseInt(item[1] * RatioInfo.scaleY),
        ]);
  });
};
// --------------------------------------------------
// 点击画点
const ClickDrawPoint = (e) => {
  debugFlag && console.log("ClickDrawPoint被调用");
  if (!drawEnd.value && !isDragging.value) {
    if (e.offsetX || e.layerX) {
      pointX.value = e.offsetX ?? e.layerX;
      pointY.value = e.offsetY ?? e.layerY;
      let piX, piY;
      if (oIndex.value > 0 && pointArr.value.length > 0) {
        // 绘制结束了
        piX = pointArr.value[0].x;
        piY = pointArr.value[0].y;
        if (judgeIsIntersect(pointArr.value)) {
          emits("pointIsIntersect");
          /*清空画布*/
          pointArr.value = [];
        } else {
          //画点
          drawMaker(ctx.value, [pointArr.value[0]], {
            randomSize: pointSize - 2,
          });
          pointArr.value.length <
            drawTypeStyle[drawTypeEnum.polygons].maxPointCount &&
            pointArr.value.push({ x: piX, y: piY });
          canvasSave(pointArr.value); //保存点线同步到另一个canvas
          saveCanvas(); //生成画布
        }
      } else {
        // 新增绘制点
        piX = pointX.value;
        piY = pointY.value;
        const pointInfo = { x: piX, y: piY };
        drawMaker(ctx.value, [pointInfo], {
          randomSize: pointSize - 2,
        });
        pointArr.value.length <
          drawTypeStyle[drawTypeEnum.polygons].maxPointCount &&
          pointArr.value.push(pointInfo);
        // 取消保存，否则线段交叉后无法清除
        // canvasSave(pointArr.value); //保存点线同步到另一个canvas
      }
    }
  }
};
// 停止拖动或者点击画点
const stopDragging = (e) => {
  debugFlag && console.log("stopDragging被调用");
  if (isDragging.value) {
    isDragging.value = false;
    const positionObj = getSelectPosition();
    const newPositions = positionObj
      .slice(selectObject.value[1])
      .concat(positionObj.slice(0, selectObject.value[1]));
    if (
      judgeIsIntersect(newPositions.map((item) => ({ x: item[0], y: item[1] })))
    ) {
      // 判断到重叠后恢复到上次绘制位置
      // 取得画布上被点击的点
      positionObj[selectObject.value[1]][0] =
        oldPointArr.value[selectObject.value[1]].x;
      positionObj[selectObject.value[1]][1] =
        oldPointArr.value[selectObject.value[1]].y;
      drawRects(res[drawTypeEnum.polygons]);
      emits("pointIsIntersect");
    }
  } else {
    ClickDrawPoint(e);
  }
};
// 鼠标移动
const MouseMove = (e) => {
  debugFlag && console.log("MouseMove被调用");
  if (!ctx.value) {
    return;
  }
  dragCircle(e);
  if (e.offsetX || e.layerX) {
    pointX.value = e.offsetX ?? e.layerX;
    pointY.value = e.offsetY ?? e.layerY;
    let piX, piY;
    /*清空画布*/
    ctx.value.clearRect(0, 0, can.value.width, can.value.height);
    /*鼠标下跟随的圆点*/
    // 将所有点反馈到操作canvas上，最后封闭时再绘制保存
    drawMaker(
      ctx.value,
      pointArr.value.concat({ x: pointX.value, y: pointY.value })
    );
    highlightPoint(e);

    if (pointArr.value.length > 0) {
      if (
        pointX.value > pointArr.value[0].x - 15 &&
        pointX.value < pointArr.value[0].x + 15 &&
        pointY.value > pointArr.value[0].y - 15 &&
        pointY.value < pointArr.value[0].y + 15
      ) {
        if (pointArr.value.length > 1) {
          piX = pointArr.value[0].x;
          piY = pointArr.value[0].y;
          oIndex.value = 1;
        }
      } else {
        piX = pointX.value;
        piY = pointY.value;
        oIndex.value = -1;
      }
      /*开始绘制*/
      ctx.value.beginPath();
      ctx.value.moveTo(pointArr.value[0].x, pointArr.value[0].y);
      if (pointArr.value.length > 1) {
        for (let i = 1; i < pointArr.value.length; i++) {
          ctx.value.lineTo(pointArr.value[i].x, pointArr.value[i].y);
        }
      }
      ctx.value.lineTo(piX, piY);
      ctx.value.fillStyle = ctxFillStyle.value; //填充颜色
      ctx.value.fill(); //填充
      ctx.value.stroke(); //绘制
    }
  }
};
/*生成画布 结束绘画*/
const saveCanvas = (pushToSave = true) => {
  debugFlag && console.log("saveCanvas被调用");
  let pointArrSaveTemp = [];
  ctx.value.clearRect(0, 0, can.value.width, can.value.height);
  drawEnd.value = true;
  ctxSave.value.closePath(); //结束路径状态，结束当前路径，如果是一个未封闭的图形，会自动将首尾相连封闭起来
  ctxSave.value.fill(); //填充
  ctxSave.value.stroke(); //绘制
  if (
    pointArr.value.length &&
    pointArr.value[0].x === pointArr.value[pointArr.value.length - 1].x &&
    pointArr.value[0].y === pointArr.value[pointArr.value.length - 1].y
  ) {
    pointArr.value.pop();
  }
  pointArr.value.forEach((item, index) => {
    pointArrSaveTemp.push([item.x, item.y]);
  });
  if (pointArrSaveTemp.length) {
    const saveInfo = { addFlag: true, positions: pointArrSaveTemp };
    res[drawTypeEnum.polygons].push(
      props.pointItemIsObj ? saveInfo : pointArrSaveTemp
    );
    pushToSave &&
      savePointInfoOfId.push(
        props.pointItemIsObj ? saveInfo : pointArrSaveTemp
      );
  }
  pointArr.value = [];
  // 限制只能画maxCount个区域
  if (
    res[drawTypeEnum.polygons].length <
    drawTypeStyle[drawTypeEnum.polygons].maxCount
  ) {
    ClickDraw();
  }
};
defineExpose({
  ClickClear,
  ClickReset,
  ClickPut,
  ClickDraw,
  ClickDrawLine,
  DeletePrevious,
  drawFullScreen,
  drawPolygons,
  deleteFullScreen,
  disabledDraw,
  judgeIsFullScreen,
  init,
});
</script>
<style lang="scss" scoped>
.canvas-wrapper {
  position: relative;
  width: 100%;
  height: 100%;
  > canvas {
    // border: 2px solid transparent;
    display: block;
  }
  .borderRed {
    // border: 2px solid #ff3d3d;
    box-shadow: 0 0 0 2px #ff3d3d inset;
  }
  .canvas-dom {
    position: absolute;
    z-index: 1;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    cursor: crosshair;
  }

  .canvasSave-dom {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
  }
  .img {
    width: 100%;
    height: 100%;
  }
}
</style>
